package com.emm.yixun.website.controller.customer;
//框架包
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.anotations.UserOperateLog;
import com.emm.yixun.common.enums.FunctionTypeEnum;
import com.emm.yixun.common.enums.ModelTypeEnum;
//变化的引用
import com.emm.yixun.common.model.Distribution;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DistributionDto;
import com.emm.yixun.common.model.dto.ExtendDistributionDto;
import com.emm.yixun.common.model.enums.CustomerOriginEnum;
import com.emm.yixun.common.model.enums.CustomerStatusEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.DistributionServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.customer.DistributionService;

@Controller
@RequestMapping("/customer/distribution/")
public class DistributionController extends BaseController<Distribution>{
	
	@Autowired
	private DistributionServiceFacade distributionServiceFacade;
	@Autowired
	private DistributionService distributionService;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));	
			map.put("intentionLevelList", IntentionLevelEnum.values());
			map.put("customerStatusList", CustomerStatusEnum.values());
			map.put("customerOriginList", CustomerOriginEnum.values());
			return "/customer/distribution/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(DistributionDto dto){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:distribution:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setDelFlag("0");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
				Response<DistributionDto> response=distributionServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:distribution:view"))){
        	try {
				Response<Distribution> response=distributionServiceFacade.findById(id);
				if(response.isSuccess()){
					ar.setSucceed(response.getEntity());
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(DistributionDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:distribution:edit"))){
        	try {
        		Response<Integer> response=distributionServiceFacade.updateByPrimaryKey(dto, true);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:distribution:delete"))){
        	try {
        		Response<Integer> response=distributionServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }
	
	
	
	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(ExtendDistributionDto dto,String startTimeStart,String startTimeEnd,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"customer:distribution:list"))){
        	try {
            	User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		if(StringUtils.isNotBlank(startTimeStart)){
        			startTimeStart=startTimeStart+" 00:00:00";
        			dto.setDistributionTimeBefore(DateUtils.StringToDate(startTimeStart, DateStyle.YYYY_MM_DD_HH_MM_SS));
                }
                
                if(StringUtils.isNotBlank(startTimeEnd)){
                	startTimeStart=startTimeEnd+" 23:59:59";
                	dto.setDistributionTimeAfter(DateUtils.StringToDate(startTimeStart, DateStyle.YYYY_MM_DD_HH_MM_SS));
                }
        		//客户等级
        		if(StringUtils.isNotBlank(dto.getIntentionLevel())){
        			List<String> intentionLevelList=new ArrayList<String>();
        			Collections.addAll(intentionLevelList, dto.getIntentionLevel().split(","));
        			dto.setIntentionLevelList(intentionLevelList);
        		}
        		//客户来源
        		if(StringUtils.isNotBlank(dto.getCustomerOrigin())){
        			List<String> list=new ArrayList<String>();
        			Collections.addAll(list, dto.getCustomerOrigin().split(","));
        			dto.setCustomerOriginList(list);
        		}
        		//客户状态
        		if(StringUtils.isNotBlank(dto.getCustomerStatus())){
        			List<String> list=new ArrayList<String>();
        			Collections.addAll(list, dto.getCustomerStatus().split(","));
        			dto.setCustomerStatusList(list);;
        		}
        		dto.setDelFlag("0");
        		dto.setIsValid("1"); //有效
        		dto.setOrders(" t.id desc ");
        		Page<ExtendDistributionDto> response=distributionServiceFacade.findExtendPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
                if(response.getSuccess()){
                    if(null==response.getRows())response.setRows(new ArrayList<ExtendDistributionDto>());
                	response.setPageNumber(pageNum);
                	ar.setSucceed(response);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	// 分配
	@RequestMapping(value = "distributionConsultant")
	@ResponseBody
	@UserOperateLog(functionName = FunctionTypeEnum.FUNCTIONTYPE_10, modelName = ModelTypeEnum.MODELTYPE_0, projectKey = "projectId")
	public AjaxRes distributionConsultant(String projectId, String ids, String customerId) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "customer:customer:distributionConsultant"))) {
			try {
				//判断被分配人id、分配人id、项目id不为空
				if(StringUtils.isBlank(ids) || StringUtils.isBlank(projectId) 
						|| StringUtils.isBlank(customerId)){
					ar.setFailMsg(Const.SAVE_FAIL);
					return ar;
				}
				String[] cusIds = ids.split("\\,");
				String sql = "";
				for(int i = 0; i < cusIds.length; i++){
					sql += cusIds[i] + "' or id = '";
				}
				if(!"".equals(sql)){
		    		sql = " id = '" + sql.substring(0, sql.length()-10);
		    	}
				
				//查询项目信息
		    	Response<Project> response = projectServiceFacade.findById(Long.parseLong(projectId));
				Project project = response.getEntity();
				
				Response<CustomerDto> res = distributionService
						.addCustomer(sql, response.getEntity(), customerId);
				ar.setSucceed(res);
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}
}
